﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WordpressDemo.Models;
using WordpressRestApi;

namespace WordpressDemo.Controllers
{
    /// <summary>Sign in Controller.</summary>
    [AllowAnonymous]
    public class SignInController : Controller
    {
        /// <summary>Sign-in the user with a code coming back from Wordpress.</summary>
        /// <param name="code">Code sent by Wordpress</param>
        /// <param name="error">Filled if Wordpress wasn't given access.</param>
        /// <returns></returns>
        public ActionResult Index(string code, string error)
        {
            if (!string.IsNullOrWhiteSpace(error))
            {
                return new HttpUnauthorizedResult();
            }
            else
            {
                var model = new SignInViewModel { AuthenticationCode = code };

                return View(model);
            }
        }

        /// <summary>Sign-in the user with wordpress app info.</summary>
        /// <param name="model">Model encapsulating information.</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Index(SignInViewModel model)
        {
            model.SetRedirectUrl(HttpContext.Request);

            if (!string.IsNullOrWhiteSpace(model.ClientID)
                && !string.IsNullOrWhiteSpace(model.ClientSecret)
                && !string.IsNullOrWhiteSpace(model.RedirectURL)
                && !string.IsNullOrWhiteSpace(model.AuthenticationCode))
            {
                var client = await WordpressClient.GetTokenAsync(
                    model.ClientID.Trim(),
                    model.ClientSecret.Trim(),
                    model.RedirectURL.Trim(),
                    model.AuthenticationCode.Trim());
                var user = await client.User.GetMeAsync();
                var identity = new IdentityModel(client.Token, user.DisplayName);

                IdentityFilterAttribute.SetIdentity(HttpContext.Response, identity);

                return RedirectToAction(null, "DemoRead");
            }
            else
            {
                return View(model);
            }
        }
    }
}